package org.example.controller;

import lombok.extern.slf4j.Slf4j;
import org.example.enums.ShortLinkStateEnum;
import org.example.service.LogService;
import org.example.service.ShortLinkService;
import org.example.util.CommonUtil;
import org.example.vo.ShortLinkVO;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @description: 用于c端调用接口
 * @author: 谢超
 * @date: 2023/8/18 15:18
 */
@Controller
@Slf4j
public class LinkApiController {

    @Resource
    private ShortLinkService shortLinkService;

    @Resource
    private LogService logService;

    @GetMapping(path = "/{shortLinkCode}")
    public void dispatch(@PathVariable(name = "shortLinkCode") String shortLinkCode, HttpServletRequest request, HttpServletResponse response) {

        try{
            log.info("短链码：{}", shortLinkCode);

            // 判断短链码是否合规
            if (isLetterDigit(shortLinkCode)) {
                // 查找短链
                ShortLinkVO shortLinkVO = shortLinkService.parseShortLinkCode(shortLinkCode);

                if (shortLinkVO != null) {
                    logService.recordShortLinkLog(request, shortLinkCode, shortLinkVO.getAccountNo());
                }

                // 判断是否过期和可用,为 true 表示未过期
                if (isVisitable(shortLinkVO)) {

                    String originalUrl = CommonUtil.removeUrlPrefix(shortLinkVO.getOriginalUrl());

                    response.setHeader("Location", originalUrl);
                    // 设置状态码302,重定向跳转
                    response.setStatus(HttpStatus.FOUND.value());
                } else {
                    response.setStatus(HttpStatus.NOT_FOUND.value());
                }
            }
        } catch (Exception e) {
            response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
        }
    }

    private static boolean isVisitable(ShortLinkVO shortLinkVO) {
        // 短链如果不为空，并且没有过期
        if (shortLinkVO != null && shortLinkVO.getExpired().getTime() > CommonUtil.getCurrentTimestamp()) {
            // 判断短链码是否可用
            return ShortLinkStateEnum.ACTIVE.name().equalsIgnoreCase(shortLinkVO.getState());
        } else if (shortLinkVO != null && shortLinkVO.getExpired().getTime() == -1) {
            return ShortLinkStateEnum.ACTIVE.name().equalsIgnoreCase(shortLinkVO.getState());
        }
        return false;
    }

    /**
     * 仅包括数字和字母
     * @param str
     * @return
     */
    private static boolean isLetterDigit(String str) {
        String regex = "^[a-z0-9A-Z]+$";
        return str.matches(regex);
    }
}
